﻿using System;
using System.Diagnostics;
using System.IO;
using System.Net;
using System.Text.RegularExpressions;
using System.Windows.Forms;
using Cassinipp.WebServer;
using CefWinform.BS;
using glTech.Log4netWrapper;
using Nancy.Hosting.Self;
using System.Collections.Generic;
using System.Net.Sockets;

namespace WebkitIISHost
{
    public partial class frmBrowser : Form
    {
        NancyHost host;
        private BsCtl bs;
      
        public frmBrowser()
        {
            InitializeComponent();
        }

        private void frmBrowser_Load(object sender, EventArgs e)
        {
            this.Text = "ZKS1000矿用钻孔深度监测装置";
            this.Text = "钻孔轨迹监测";

//            StartWebSite(SystemConfig.AppPort, SystemConfig.VirtRoot, SystemConfig.AppPath);
            StartNancyWebSite(SystemConfig.AppPort);
//            var url = string.Format(" http://localhost:{0}/Coordinates/tracking-3d.html", SystemConfig.AppPort);
            bs = new BsCtl(panelCanvas, SystemConfig.DefaultUrl);

            Logger.LogInfo("转到网址" + SystemConfig.DefaultUrl);
        }

        private void StartNancyWebSite(int port)
        {
            try
            {
                // this forces ACL to create network rules for new ports if not already exist
                var hostConfiguration = new HostConfiguration
                {
                    UrlReservations = new UrlReservations() { CreateAutomatically = true }
                };
                host = new NancyHost(hostConfiguration, GetUriParams(port));
                host.Start();

             
            }
            catch (Exception ex)
            {
                Logger.LogError(ex.Message);
            }
        }

        private Uri[] GetUriParams(int port)
        {
            var uriParams = new List<Uri>();
            string hostName = Dns.GetHostName();

            // Host name URI
            string hostNameUri = string.Format("http://{0}:{1}", Dns.GetHostName(), port);
            uriParams.Add(new Uri(hostNameUri));

            // Host address URI(s)
            var hostEntry = Dns.GetHostEntry(hostName);
            foreach (var ipAddress in hostEntry.AddressList)
            {
                if (ipAddress.AddressFamily == AddressFamily.InterNetwork)  // IPv4 addresses only
                {
                    var addrBytes = ipAddress.GetAddressBytes();
                    string hostAddressUri = string.Format("http://{0}.{1}.{2}.{3}:{4}", addrBytes[0], addrBytes[1], addrBytes[2], addrBytes[3], port);
                    uriParams.Add(new Uri(hostAddressUri));
                }
            }

            // Localhost URI
            uriParams.Add(new Uri(string.Format("http://localhost:{0}", port)));
            return uriParams.ToArray();
        }

        private void StartWebSite(int port, string virtRoot, string appPath)
        {
            try
            {
                Server server;
                string RegexString = @"[a-zA-Z]:\\.*";
                var ma = Regex.Match(appPath, RegexString);
                if (ma.Success)
                {
                    server = new Server(port, virtRoot, appPath, true ? IPAddress.Any : IPAddress.Loopback);
                }
                else
                {
                    var path = Path.Combine(Application.StartupPath, appPath);
                    server = new Server(port, virtRoot, path, true ? IPAddress.Any : IPAddress.Loopback);
                }

                server.Start();
                Logger.LogInfo("启动Host成功。");
            }
            catch (Exception ex)
            {
                Logger.LogError("启动Host出错。");
                Logger.LogError4Exception(ex);
            }
        }

        private void webSiteToolStripMenuItem_Click(object sender, EventArgs e)
        {
            var child = new frmWebSiteSetting();
            child.ShowDialog();
        }

        private void readCardToolStripMenuItem_Click(object sender, EventArgs e)
        {
            var child = new frmReadCardSetting();
            child.ShowDialog();
        }

        private void tsmBrowser_Click(object sender, EventArgs e)
        {
            gbBrowser.Visible = !gbBrowser.Visible;
        }

        private void btnBrowser_Click(object sender, EventArgs e)
        {
            var url = txbUrl.Text;
            bs.LoadUrl(url);
            SystemConfig.DefaultUrl = url;
            SystemConfig.Save();

            Logger.LogInfo("转到网址" + url);
//            bs = new BsCtl(panelCanvas, url);
        }

//        protected override void WndProc(ref Message m)
//        {
//            if (m.Msg == 0x112)
//            {
//                switch ((int)m.WParam)
//                {
//                    //禁止双击标题栏关闭窗体
//                    case 0xF063:
//                    case 0xF093:
//                        m.WParam = IntPtr.Zero;
//                        break;
//
//                    //禁止拖拽标题栏还原窗体
//                    case 0xF012:
//                    case 0xF010:
//                        m.WParam = IntPtr.Zero;
//                        break;
//
//                    //禁止双击标题栏
//                    case 0xf122:
//                        m.WParam = IntPtr.Zero;
//                        break;
//
//                    //禁止关闭按钮
//                    case 0xF060:
//                        m.WParam = IntPtr.Zero;
//                        break;
//
//                    //禁止最大化按钮
//                    case 0xf020:
//                        m.WParam = IntPtr.Zero;
//                        break;
//
//                    //禁止最小化按钮
//                    case 0xf030:
//                        m.WParam = IntPtr.Zero;
//                        break;
//
//                    //禁止还原按钮
//                    case 0xf120:
//                        m.WParam = IntPtr.Zero;
//                        break;
//                }
//            }
//            base.WndProc(ref m);
//        }
    }
}
